package org.rbio.paper.methylglm.annotate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.broadinstitute.sting.gatk.datasources.reference.ReferenceDataSource;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.codecs.refseq.RefSeqCodec;
import org.broadinstitute.sting.utils.codecs.refseq.RefSeqFeature;

// helper class to make genes from UCSC transcript tables
public class UCSCGeneTable {

	// read UCSC gene file
	public static Map<String, Map<String, List<RefSeqFeature>>> read(
			String fname, String fa) throws Exception {
		// result map [ref [gene name [tx]]]
		Map<String, Map<String, List<RefSeqFeature>>> gene_ref_tab = new LinkedHashMap<String, Map<String, List<RefSeqFeature>>>();

		// rnaseq codec
		ReferenceDataSource data_src = new ReferenceDataSource(new File(fa));
		GenomeLocParser parser = new GenomeLocParser(data_src.getReference());
		RefSeqCodec codec = new RefSeqCodec();
		codec.setGenomeLocParser(parser);

		// parse the file
		BufferedReader ibuf = new BufferedReader(new FileReader(fname));
		String line = ibuf.readLine();
		while ((line = ibuf.readLine()) != null) {
			// blank line
			if (line.length() == 0) {
				continue;
			}

			// parse tx
			RefSeqFeature tx = codec.decode(line);

			// add to the table
			Map<String, List<RefSeqFeature>> gene_tab = gene_ref_tab.get(tx
					.getChr());
			if (gene_tab == null) {
				gene_tab = new LinkedHashMap<String, List<RefSeqFeature>>();
				gene_ref_tab.put(tx.getChr(), gene_tab);
			}
			List<RefSeqFeature> gene = gene_tab.get(tx.getGeneName());
			if (gene == null) {
				gene = new ArrayList<RefSeqFeature>();
				gene_tab.put(tx.getGeneName(), gene);
			}
			gene.add(tx);
		}

		// done !
		return gene_ref_tab;
	}
}
